package com.cash.loan.modular.cash.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.cash.loan.core.upload.QiniuService;
import com.cash.loan.modular.cash.dao.LoanArticleTypeMapper;
import com.cash.loan.modular.cash.dao.LoanStrategyMapper;
import com.cash.loan.modular.cash.model.LoanArticleType;
import com.cash.loan.modular.cash.model.LoanStrategy;
import com.cash.loan.modular.cash.result.PageResult;
import com.cash.loan.modular.cash.result.ServerResponse;
import com.cash.loan.modular.cash.service.StrategyService;
import com.cash.loan.modular.cash.transfer.CreateStrategyDto;
import com.cash.loan.modular.cash.transfer.ImageItem;
import com.cash.loan.modular.cash.transfer.LoanStrategyListVo;
import com.cash.loan.modular.cash.transfer.UpdateStrategyDto;
import com.cash.loan.modular.cash.util.PageBeanUtil;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author Administrator
 * @Date 2018-07-20 9:05
 */
@Service
public class StrategyServiceImpl implements StrategyService{

    @Autowired
    private LoanStrategyMapper strategyMapper;

    @Autowired
    private LoanArticleTypeMapper articleTypeMapper;

    @Autowired
    private QiniuService qiniuService;

    @Override
    public PageResult<LoanStrategyListVo> getLoanStrategyList(String keyword, Date sDate, Date eDate, Integer currentPage, Integer pageSize) {
        PageHelper.startPage(currentPage,pageSize);
        List<LoanStrategyListVo> loanStrategyListVoList =  strategyMapper.getLoanStrategyList(keyword,sDate,eDate);
        List<LoanStrategyListVo> dealList = new ArrayList<>();
        loanStrategyListVoList.stream().forEach(
                loanStrategyListVo -> {
                    if(loanStrategyListVo.getViewNum() == null) {
                        loanStrategyListVo.setViewNum(0L);
                    }
                    if(StringUtils.isBlank(loanStrategyListVo.getCateName())) {
                        loanStrategyListVo.setCateName("");
                    }
                    dealList.add(loanStrategyListVo);
                }
        );
        PageResult<LoanStrategyListVo> pageResult = PageBeanUtil.toPageResult(loanStrategyListVoList);
        pageResult.setDataList(dealList);
        return pageResult;
    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public Boolean createStrategy(CreateStrategyDto strategyDto) {
        LoanStrategy loanStrategy = new LoanStrategy();
        loanStrategy.setTitle(strategyDto.getTitle());
        List<ImageItem> imageItemList = strategyDto.getUrl();
        imageItemList.stream().forEach(imageItem -> {
            imageItem.setUrl(qiniuService.getUri(imageItem.getUrl()));
        });
        String imageListJsonString = JSONArray.toJSONString(imageItemList);
        loanStrategy.setImgUrlList(imageListJsonString);
        String content = JSONArray.toJSONString(strategyDto.getContent());
        loanStrategy.setContent(content);
        loanStrategy.setCateId(strategyDto.getCateId());
        strategyMapper.insert(loanStrategy);
        return true;
    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public Boolean updateStrategy(UpdateStrategyDto strategyDto) {
        LoanStrategy loanStrategy = new LoanStrategy();
        loanStrategy.setId(strategyDto.getId());
        loanStrategy.setTitle(strategyDto.getTitle());
        List<ImageItem> imageItemList = strategyDto.getUrl();
        imageItemList.stream().forEach(imageItem -> {
            imageItem.setUrl(qiniuService.getUri(imageItem.getUrl()));
        });
        String imageItemListJsonStr = JSONArray.toJSONString(imageItemList);
        loanStrategy.setImgUrlList(imageItemListJsonStr);
        String content = JSONArray.toJSONString(strategyDto.getContent());
        loanStrategy.setContent(content);
        loanStrategy.setCateId(strategyDto.getCateId());
        strategyMapper.updateById(loanStrategy);
        return true;
    }

    @Override
    public Map<String, Object> getStrategyContentById(Long id) {
        Map<String,Object> map = strategyMapper.getStrategyContentById(id);
        Map<String,Object> result = new HashMap<>();
        if(map == null || map.size() == 0) {
            return result;
        }
        result.put("cateId",map.get("cateId"));
        if(StringUtils.isNotBlank((String)map.get("cateName"))) {
            result.put("cateName",map.get("cateName"));
        } else {
            result.put("cateName","");
        }
        result.put("title",map.get("title"));
        if(StringUtils.isBlank((String)map.get("imgUrlList"))) {
            result.put("imgUrlList",new JSONArray());
        } else {
            String imageItemString = (String) map.get("imgUrlList");
            List<ImageItem> imageItemList = JSONArray.parseArray(imageItemString,ImageItem.class);
            imageItemList.stream().forEach(imageItem ->
                imageItem.setUrl(qiniuService.getUrl(imageItem.getUrl()))
            );
            result.put("imgUrlList",imageItemList);
        }
        JSONArray jsonArray = JSONArray.parseArray((String) map.get("content"));
        result.put("content",jsonArray);
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String createTime = format.format((Date)map.get("createTime"));
        result.put("createTime",createTime);
        return result;
    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public Boolean deleteById(Long id) {
        strategyMapper.deleteById(id);
        return true;
    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public ServerResponse updateOldData() {
        List<LoanStrategy> loanStrategyList = strategyMapper.selectList(new EntityWrapper<LoanStrategy>());
        loanStrategyList.stream().forEach(loanStrategy -> {
            if (!loanStrategy.getImgUrlList().contains("[")) {
                String urlStr = loanStrategy.getImgUrlList();
                ImageItem imageItem = new ImageItem();
                imageItem.setType("smallPic");
                imageItem.setUrl(urlStr);
                List<ImageItem> imageItemList = new ArrayList<>();
                imageItemList.add(imageItem);
                String urlJsonStr = JSONArray.toJSONString(imageItemList);
                loanStrategy.setImgUrlList(urlJsonStr);
                strategyMapper.updateById(loanStrategy);
            }
        });
        return ServerResponse.getSuccess("更新成功");
    }

    @Override
    public List<Map<String, Object>> getCateList() {
        List<LoanArticleType> articleTypeList = articleTypeMapper.selectList(new EntityWrapper<LoanArticleType>());
        List<Map<String,Object>> list = new ArrayList<>();
        articleTypeList.stream().forEach(loanArticleType -> {
            Map<String,Object> map = new HashMap<>();
            map.put("id",loanArticleType.getId());
            map.put("name",loanArticleType.getName());
            list.add(map);
        });
        return list;
    }


}
